<template>
  <div>
    <contact-summary-solt  v-loading="loading" v-show="this.$route.path.split('/')[2] === 'call'">
      <!--解决通话详情点开之后，第一次加载其他模块时，右侧会闪一下才消失的问题-->
      <template slot="customerSlot">
        <customer-slot
          :customer="customer"
          :custType="custType"
          :currentBusinessObj="currentBusinessObj"
          :isDailog="isDailog"
          @addCustomer="addCustomer"
          @merged="mergeCustomer"
          @requestUpdateCustInfo="handleRequestUpdateCustInfo"
        ></customer-slot>
      </template>
      <template slot="funTabSlot">
        <fun-tab-slot :tabs="tabs" :activeName="tabActiveName" @handleEditTab="handleEditTab" @changeDetailTab="handlerChangeTab" :urlsStres="urlsStr" :tabType="tabType" :isShowToolbar="true">
          <template slot="goldenSessionTab" v-if="showTabIntelligent ">
            <golden-session   :refresh = 'refresh'  :reload='randomTime'  v-if="showTabIntelligent"></golden-session>
          </template>
          <template slot="callDetailTab">
            <!--callDetail是文件夹  默认走index.vue-->
            <call-detail v-if="callCount > 0" :refresh="refresh" :curModel="true" :key="callData" :getCurrentCallData="callData" audioId="callDetailAudio"></call-detail>
          </template>
          <template slot="businessTab">
            <guide1 :customer="customer"
                   :custType="custType"
                   @merged="mergeCustomer"
                   @addCustomer="addCustomer"
                   v-if="!isTargetCustomers"
                   :currentBusinessObj="currentBusinessObj"></guide1>
            <business
              v-if="isTargetCustomers"
              :cacheId="callSheetId"
              :busId="busId"
              :refresh="refresh"
              :reload='reloadBussiness'
              :custInfo="customer"
              :cid="cid"
              :callInfo="$store.state.call.current[this.tabType] && $store.state.call.current[this.tabType].callInfo"
              :linkData="buslinkData"
              :showHistoryTable="true"
              :showbusRelatedTable="true"
              @event="businessEvent"
              :businessNumbers="callData && callData.ASSOCIATED_BUSINESSES"
              link="call"></business>
          </template>
          <template slot="contactPlanTab" v-if="!loading">
            <guide1 :customer="customer"
                   :custType="custType"
                   @merged="mergeCustomer"
                   @addCustomer="addCustomer"
                   v-if="!isTargetCustomers"
                   :currentBusinessObj="currentBusinessObj"></guide1>
            <contact-plan
              v-if="isTargetCustomers"
              :refreshBusRight="refreshBusRight"
              :refresh="refresh" :cid="cid"></contact-plan>
          </template>
          <template slot="historyTab" v-if="!loading">
            <guide1 :customer="customer"
                   :custType="custType"
                   @addCustomer="addCustomer"
                   @merged="mergeCustomer"
                   v-if="!isTargetCustomers"
                   :currentBusinessObj="currentBusinessObj"></guide1>
            <contact-history v-if="isTargetCustomers" :refresh="refresh" :cid="cid"></contact-history>
          </template>
          <template slot="changeLogTab" v-if="!loading">
            <guide1 :customer="customer"
                   :custType="custType"
                   @merged="mergeCustomer"
                   @addCustomer="addCustomer"
                   v-if="!isTargetCustomers"
                   :currentBusinessObj="currentBusinessObj"></guide1>
            <operation-log v-if="isTargetCustomers && (this.$store.state.session.account.isSouthEastAsia !== 'true')" :refresh="refresh" :cid="cid" :refreshBusRight="refreshBusRight"></operation-log>
          </template>
          <!--refresh.indexOf('item') > -1 当前的activeName是iframe才进行加载-->
          <template v-if="tabCount > 1" v-for= "item in tabUrls" :slot="item._id">
            <div :class="item.businesses && item.businesses.length > 0 ? 'moreIframe-wrap' : 'iframe-wrap'">
              <div v-if="item.businesses && item.businesses.length > 0" class="moreIframe-wrap">
                <div clss="businessesSelect" style="margin: 10px">业务类型</div>
                <el-select v-model="toolBarValue" filterable placeholder="请选择" style="margin: 0px 10px 10px">
                  <el-option
                    v-for="(toolBarItem, index) in item.businesses"
                    :key="index"
                    :label="toolBarItem.name"
                    :value="toolBarItem.url">
                  </el-option>
                </el-select>
                <iframe v-if="toolBarValue !== ''" :src="newUrl(toolBarValue)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
              </div>
              <iframe v-else :src="newUrl(item.url, item.isEncode)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
            </div>
          </template>
        </fun-tab-slot>
        <editTab :tabs="toolTabs" :type="'call'" ref="editCallTab" @updateTabConfig="updateTabConfig"></editTab>
      </template>
    </contact-summary-solt>
  </div>
</template>
<script>
  function getToken (store) {
    return store.dispatch('getToken')
  }
  // 此组件是通话右侧详情
  import {isHasMenu, encrypt, deepClone, getAesEncrypt} from '@/utils/m7Utils'
  import editTab from '@/components/business-modules/webchat/webchat-right/customer-Information/dialog/editTab'
  import guide1 from '@/components/public-modules/cust-tab-content/guide/index.vue'
  import ContactSummarySolt from '@/components/public-modules/contact-summary/index.vue'
  import CustomerSlot from '@/components/public-modules/contact-summary/CustomerSlot'
  import FunTabSlot from '@/components/public-modules/contact-summary/FunTab'
  import OperationLog from '@/components/public-modules/cust-tab-content/operation-log/'
  import ContactPlan from '@/components/public-modules/cust-tab-content/contact-plan/'
  import ContactHistory from '@/components/public-modules/cust-tab-content/contact-history/'
  import Business from '@/components/public-modules/cust-tab-content/business/'
  import CallDetail from '@/components/public-modules/cust-tab-content/call-detail'
  import GoldenSession from '@/components/public-modules/cust-tab-content/goldenSession'
  import { isEmpty } from 'lodash'
  import * as globalTypes from 'src/store/mutation-types'
  import bus from '@/store/eventBus'
  import md5 from 'md5'
  // import { transferFileContent } from '@/utils/webchat'
  export default {
    name: 'CallSummary',
    data () {
      return {
        callCount: 0,
        callSheetId: '',
        tabActiveName: 'callDetail',
        loading: true,
        refresh: 'callDetail',
        bussinessType: 'call',
        isDailog: true,
        timestamp: '',
        tabUrls: [], // tab对接的url数据
        urlsStr: [], // tab对接弹出的url数据
        token: '',
        toolbarTab: [],
        businessFirstIn: true, // 第一次进入工单时才加载工单数据，tab再次切换不加载
        busId: '',
        cid: '',
        toolBarValue: '',
        tabs2: {
          normalTab: [
            // {disabled: false, name: 'callDetail', slotName: 'callDetailTab', labelName: this.$t('public.callDetails')},
            // {disabled: false, name: 'business', slotName: 'businessTab', labelName: this.$t('public.business')},
            // {disabled: false, name: 'plan', slotName: 'contactPlanTab', labelName: this.$t('public.contactPlan')}
          ],
          tabUrl: {disabled: false}
        },
        reloadBussiness: 0, // 重新加载工单
        tabCount: 1, // 控制tab对接页点开右侧时不加载，点击之后加载，加载之后再次切换不再重新加载资源
        isTargetCustomers: true, // 是展示联系历史，操作日志等还是显示添加客户页面的标志
        tabType: '', // 左侧tab类型
        randomTime: 0,
        intelligentData: [], // 金牌话术数据
        tempTab: []
      }
    },
    computed: {
      callData () {
        if (this.tabType === 'cdr_all' || this.tabType === 'cdr_pending' || this.tabType === 'cdr_outbound') { // 全部 || 待处理往子组件传当前的通话数据
          return this.$store.state.call.current[this.tabType].callInfo || {}
        }
        return {}
      },
      routeName(){
        return this.$route.path.split('/')[3]
      },
      showIntelligent(){
        return this.$store.state.call.showIntelligent
      },
      transferNoInteligent(){
        return this.$store.state.call.transferNoInteligent
      },
      showTabIntelligent(){
        if(this.showIntelligent && !this.transferNoInteligent){
          return true
        }else{
          return false
        }
      },
      refreshBusRight () { // 点击卡片刷新右侧
        return this.$store.state.call.transCache.refreshCustRight
      },
      // cid () { // 获取当前客户id
      //   let routes = this.$route.path.split('/')
      //   let tabType = routes[3]
      //   if (routes[2] === 'call' && tabType) { // 确保是在call模块再取currentCustomer
      //     let currentCustomer = this.$store.state.call.current[tabType].currentCustomer
      //     if (currentCustomer) {
      //       return currentCustomer._id
      //     } else {
      //       return ''
      //     }
      //   }
      // },
      customer () {
        const isEnglis = window.localStorage.lang || 'zh_CN'
        let routes = this.$route.path.split('/')
        let tabType = routes[3]
        if (routes[2] === 'call' && tabType) {
          let screenCallSheetId = this.$store.state.cti.globalLet.outboundScreenCallSheetId
          let currentCustomer = this.$store.state.call.current[tabType].currentCustomer
          if (screenCallSheetId && screenCallSheetId === routes[4] && tabType === 'cdr_outbound') {
            // 当前通话中的id === 卡片点击的id, 取临时存储的右侧客户信息（还未生成通话记录）
            currentCustomer = this.$store.state.call.transCache.tempCustomerData.customer || {}
            this.$store.commit('call/SET_CALL_INFO_CUSTOMER_ID', {data: currentCustomer._id, type: 'cdr_outbound'})
          }
          let tel = ''
          let callObj = this.$store.state.call.current[tabType]
          let isUnknowCust = ''
          if (callObj) {
            let callInfo = callObj.callInfo
            if (callInfo) {
              if (callInfo.CONNECT_TYPE === 'normal' || callInfo.CONNECT_TYPE === 'transfer') {
                tel = callInfo.CALL_NO
              } else {
                tel = callInfo.CALLED_NO
              }
//              callInfo.CUSTOMER_ID = '00000000000000000000'
              if (callInfo.CUSTOMER_ID === '00000000000000000000' || !callInfo.CUSTOMER_ID) {
                isUnknowCust = true
              }
            }
          }
          let phone = {phone: [{tel, memo: ''}]}
          if (isEnglis === 'en' && isUnknowCust && currentCustomer) {
            if (currentCustomer.name === '多个匹配客户') {
              currentCustomer.name = this.$t('customer.customerSlot.unlocation')
            } else if (currentCustomer.name === '未知客户') {
              currentCustomer.name = this.$t('public.unknownCustomer')
            }
          }
          return isEmpty(currentCustomer) ? phone : currentCustomer
        }
      },
      custType () { // 客户类型 eg: 定位到一个客户or 未知客户
        let routes = this.$route.path.split('/')
        let tabType = routes[3]
        if (routes[2] === 'call' && tabType) {
          return this.$store.state.call.current[tabType].currentCustomer ? 'one' : 'unk'
        }
      },
      currentBusinessObj () {
        // 传递给客户模块的业务信息
        let routes = this.$route.path.split('/')
        if (routes[2] === 'call') {
          let tabType = routes[3]
          let callId = routes[4]
          return {tabType: tabType, type: this.bussinessType, callId: callId}
        } else {
          return {tabType: '', type: '', callId: ''}
        }
      },
      // 通话提交工单添加的信息
      buslinkData () {
        let data = this.$store.state.call.current[this.tabType].callInfo || {}
        return {callNo: data.CALL_NO, callSheetId: data.CALL_SHEET_ID, offeringTime: data.OFFERING_TIME}
      },
      tabs () {
        this.isTargetCustomers = true
        if (this.tabType && this.cid !== '') {
          let customer = this.$store.state.call.current[this.tabType].currentCustomer
          if (isEmpty(customer)) { // 没有定位到客户
            this.isTargetCustomers = false
          } else {
            this.isTargetCustomers = true
          }
        } else {
          this.isTargetCustomers = false
        }
        return this.tabs2
      },
      toolTabs () {
        let toolTabs = []
        let tabs = deepClone(this.tabs.normalTab)
        for (let i in tabs) {
          toolTabs.push({...tabs[i]})
        }
        return toolTabs
      }
    },
    watch: {
      refreshBusRight (cur, old) {
        let currentType = this.$route.path.split('/')[3]
        if (currentType === 'cdr_call') {
          return
        }
        this.businessFirstIn = true
        this.fetchData()
        this.randomTime = Math.random()

        this.tabActiveName = this.tabs2.normalTab[0].slotName ? this.tabs2.normalTab[0].name : this.tabs2.normalTab[0]._id
        if (this.refresh.indexOf('-') > -1) {
          this.tabCount = 2
        } else {
          this.tabCount = 1
        }
        if (this.refresh === 'callDetail') {
          this.callCount += 1
        } else {
          this.callCount = 0
        }
      }
    },
    components: {
      guide1,
      ContactSummarySolt,
      CustomerSlot,
      FunTabSlot,
      Business,
      ContactPlan,
      ContactHistory,
      OperationLog,
      CallDetail,
      GoldenSession,
      editTab
    },
    methods: {
      showTab(val){
        console.log(val)
      },
      addCustomer(val, data) {
        if (data) {
          this.cid = data._id
        } else {
          this.cid = val._id
        }
        this.loading = false
      },
      editCustomer () {
        // this.loading = false
      },
      isHaveMenu (func) {
        return isHasMenu(func, this.$store.state.session.user)
      },
      handleEditTab () {
        this.$refs.editCallTab.open()
      },
      updateTabConfig (val) {
        this.$store.dispatch('saveToolbarTabPosition', {module: 'call', tabs: val}).then(res => {
          this.tabs2.normalTab = val
          this.intelligentData = val
          this.tabActiveName = this.tabs2.normalTab[0].slotName ? this.tabs2.normalTab[0].name : this.tabs2.normalTab[0]._id
          this.refresh = this.tabs2.normalTab[0].slotName ? this.tabs2.normalTab[0].name : this.tabs2.normalTab[0]._id
          if (this.refresh.indexOf('-') > -1) {
            this.tabCount = 2
          }
          if (this.refresh === 'callDetail') {
            this.callCount += 1
          } else {
            this.callCount = 0
          }
          this.tabUrlHandle()
          bus.$emit('saveCallToolBar')
        })
      },
      businessEvent (eventData) { // 工单操作事件外抛
        let data = eventData.data
        this.busId = data._id
        if (eventData.event !== 'changeBusinessMaster') {
          this.$store.dispatch('getBusinessDetailById', {_id: this.busId})
        }
        console.log(eventData.event,'eventData.event')
        if(eventData.event !== 'addTempBusinessTask') {
          this.fetchData()
        }
        this.$store.commit('business/REFRESH_CUSTOMER_BUSINESS_HISTORY', this.cid)
        // 刷新新版工单左侧菜单栏数量统计
        this.$store.commit('business/REFRESH_MENUBAR',Math.random())
      },
      fetchData (flag) {  // 查数据
        let account = this.$store.state.session.account
        if (['T00000022274', 'T00000024274', 'T00000000003'].includes(account.account) && account.encryType === 'aes') { // 顺丰定制 && 开启了aes加密
          const timestamp = new Date().getTime()
          this.timestamp = timestamp
        }
        if (!this.showTabIntelligent) {
          this.tabs2.normalTab = this.tabs2.normalTab.filter(item => {
            return item.name !== 'goldenSession'
          })
        } else {
          this.tabs2.normalTab = this.intelligentData
          let isExist = this.tabs2.normalTab.some(item => {
            if (item.name == 'goldenSession') {
              return true
            } else {
              return false
            }
          })
          if (!isExist) {
            if (this.tempTab.length) {
              this.tabs2.normalTab.unshift(this.tempTab[0])
              this.updateTabConfig(this.tabs2.normalTab)
              this.loading = false
            }
          }
        }
        if (!flag) {
          this.refresh = this.tabs2.normalTab[0].slotName ? this.tabs2.normalTab[0].name : this.tabs2.normalTab[0]._id
        } else {
          this.refresh = this.tabActiveName
        }
        let routes = this.$route.path.split('/')
        this.loading = true
        let tabType = routes[3]
        if (routes[2] !== 'call' || !routes[4]) {
          return
        }
        let data = { data: routes[4], type: routes[3] }
        this.callSheetId = routes[4]
        let screenCallSheetId = this.$store.state.cti.globalLet.outboundScreenCallSheetId
        let tempCustData = this.$store.state.call.transCache.tempCustomerData
        if (screenCallSheetId && screenCallSheetId === routes[4]) { // 当前通话中的id === 卡片点击的id, 取临时存储的右侧客户信息（还未生成通话记录）
          this.outboundFetchData(tempCustData, routes[4])
        } else {
          return this.$store.dispatch('relocationCustomer', data).then(resp => { // 定位客户（已生成通话记录）
            this.loading = false
            if (resp && resp.success) { // 已生成通话记录
              if (resp.list.length === 1) {
                  this.cid = resp.list[0]._id
                } else {
                  this.cid = ''
                }
              if (tabType === 'cdr_my' || tabType === 'cdr_pending' || tabType === 'cdr_all') { // 其他情况下不需要请求ivr轨迹和转接轨迹
                this.$store.dispatch('queryTransferContrail', {data: resp.row, type: tabType}) // 转接轨迹：通话类型为转接或者是外呼转接
                if (resp.row && (resp.row.CONNECT_TYPE === 'normal' || resp.row.CONNECT_TYPE === 'transfer')) { // 来电和来电转接的情况下

                  this.$store.dispatch('queryIvrContrail', resp.row.CALL_SHEET_ID).then(response => {
                    if (response && response.success) {
                      this.$store.commit('call/QUERY_IVR_CONTRAIL', {data: response.data, type: tabType}) // ivr轨迹
                    }
                  }).catch((e) => {
                    console.log(e)
                  })
                }
                if (resp.row && resp.row.REPEAT_CALL) { // 若是重复来电则请求通话历史
                  let historyData = {'CALL_NO': resp.row.CALL_NO, 'OFFERING_TIME': resp.row.OFFERING_TIME, 'page': 1, 'limit': 10}
                  this.$store.dispatch('queryLatestedCallSheet', {data: historyData, type: tabType})
                }
              }
              this.tabUrlHandle()
              if (this.tabType === 'cdr_outbound' && routes[4]) {
                // this.handlerChangeTab('business')
                this.$store.commit('IS_CALL_OUT_INTERFACE', {status: true}) // 是否要显示iframe组件
                if (resp.count === -1) { // 当前客户已删除,再次点击去电卡片的时，要变更为添加组件
                  this.updateOutboundList(routes[4])
                }
              }
            } else {
              if (this.tabType === 'cdr_outbound' && routes[4]) { // 请求失败 && 当前是去电模块取临时数据
                this.outboundFetchData(tempCustData, routes[4])
              }
            }
            if (this.refresh === 'business') {
              this.busId = ''
              if (this.businessFirstIn) { // 第一次进入工单时才加载工单数据，tab再次切换不加载
                this.reloadBussiness = Math.random()
                this.businessFirstIn = false
              }
            }
          })
        }
      },
      updateOutboundList (callSheetId) {
        let callInfo = null
        let localList = []
        let sessionList = window.sessionStorage.getItem('callOutList')
        if (sessionList && sessionList !== 'undefined') {
          localList = JSON.parse(sessionList)
        }
        if (!localList || localList === 'undefined') {
          localList = []
        }
        let list = this.$store.state.call.callList.cdr_outbound.list || localList
        // 判断是否有通话id相关的详情
        for (let i = 0; i < list.length; i++) {
          if (list[i]._id === callSheetId) {
            callInfo = list[i]
          }
        }
        if (callInfo) {
          callInfo.CUSTOMER_TYPE = 'unk'
        }
        bus.$emit('updateOutboundRight')
      },
      outboundFetchData (tempCustData, callSheetId) {
        this.loading = false
        // this.handlerChangeTab('business')
        if (tempCustData && tempCustData.callId === callSheetId) { // 说明通话中有操作添加或者是合并客户
          this.$store.commit('call/UPDATE_CURRENT_CUSTOMER_INFO', {callId: tempCustData.callId, customer: tempCustData.customer}) // 更新当前通话记录的客户信息
          this.cid = tempCustData.customer._id
        }
        this.tabUrlHandle()
        this.$store.commit('IS_CALL_OUT_INTERFACE', {status: true}) // 是否要显示iframe组件
      },
      tabUrlHandle () {
        let tabUrles = this.tabs2.normalTab || []
        if (tabUrles && tabUrles.length > 0) { // 有tab对接的数据&&有获取token权限时才会去取token
          this.urlsStr = [] // 解决卡片切换之后不断地往里面push的问题
          if (this.$store.state.session.account.tokenCheck) {
            getToken(this.$store).then((token) => {
              this.token = token
              tabUrles.forEach(item => {
                this.urlsStr.push(this.newUrl(item.url ? item.url.replace('http://', '//') : ''))
              })
            })
          } else {
            tabUrles.forEach(item => {
              this.urlsStr.push(this.newUrl(item.url ? item.url.replace('http://', '//') : ''))
            })
          }
        }
      },
      handleRequestUpdateCustInfo (done) { // 点击修改客户归属的时候，刷新一下数据，避免A坐席修改归属之后，B坐席看到的还是旧的，直接覆盖A坐席的修改
        try {
          var promise = this.fetchData('updateCustInfo')
          if (!promise) {
            done()
          } else {
            promise.then(() => {
              this.$store.commit(globalTypes.UPDATE_CUSTOMER_INFO, {data: this.customer})
              done()
            })
          }
        } catch (error) {
          done()
        }
      },
      newUrl (url, isEncode) { // tab对接数据拼接
        let routes = this.$route.path.split('/')
        let tabType = routes[3]
        let callSheetId = routes[4] || ''
        if (routes[2] !== 'call' || !callSheetId) { // 切换到其他模块或者是没有到详情的页面的时候，不传参
          return ''
        }
        let callInfo = {}
        if (this.$store.state.call.current[tabType]) {
          callInfo = this.$store.state.call.current[tabType].callInfo || {}
        }
        let diaplayName = this.$store.state.session.user.displayName || ''
        let exten = this.$store.state.session.user.exten || ''
        if (url) {
          if (url.indexOf('?') === -1) {
            url += '?'
          } else {
            url += '&'
          }
        }
        if (this.tabType === 'cdr_outbound' && routes[4]) {
          url += 'tabType=customer'
        } else {
          url += 'tabType=call'
        }
        let message = ''
        const account = this.$store.state.session.account
        if (callInfo && callInfo.CUSTOMER_ID && callInfo.CUSTOMER_ID !== '' && callInfo.CUSTOMER_ID !== '00000000000000000000' && this.currentCustomer !== {}) {
          let currentCustomer = this.customer
          let city = currentCustomer.city || ''
          let province = currentCustomer.province || ''
          if (city && province) {
            let list = {}
            let newOptions = this.$getCache('options')
            for (let ind in newOptions) {
              if (newOptions[ind].accountId === 'system' && newOptions[ind].name === '省市县') { // 后端字段是中文，此判断不能国际化
                list = newOptions[ind].options
              }
            }
            for (let i = 0; i < list.length; i++) {
              if (list[i].key === province) {
                for (let j = 0; j < list[i].options.length; j++) {
                  if ((list[i].options[j]).key === city) {
                    city = list[i].options[j].name
                  }
                }
                province = list[i].name
              }
            }
          }
          let custTmpls = this.$getCache('custTmpls')
          let custStatusName = custTmpls[0].status[currentCustomer.status] || ''
          let calledTel = ''
          let callPhone = ''
          if (callInfo.CONNECT_TYPE === 'dialout' || callInfo.CONNECT_TYPE === 'dialTransfer') {
            calledTel = callInfo.CALL_NO
            callPhone = callInfo.CALLED_NO
          } else {
            calledTel = callInfo.CALLED_NO
            callPhone = callInfo.CALL_NO
          }
          if (custTmpls && custTmpls.length > 0 && custTmpls[0].template_type !== 'company') { // 个人版本
            let sex = ''
            if (currentCustomer.sex) {
              if (currentCustomer.sex === '0') {
                sex = this.$t('public.male')
              } else if (currentCustomer.sex === '1') {
                sex = this.$t('public.famel')
              }
            }
            message += '&name=' + (currentCustomer.name || '') + '&status=' + (custStatusName || '') + '&title=' + (currentCustomer.title || '') + '&phone=' + this.arrToStr(currentCustomer.phone, 'tel') + '&callPhone=' + this.arrToStr([{calledTel, memo: ''}], 'calledTel') + '&email=' + this.arrToStr(currentCustomer.email, 'email') +
                    '&weixin=' + this.arrToStr(currentCustomer.weixin, 'num') + '&province=' + (province || '') + '&city=' + (city || '') + '&address=' + (currentCustomer.address || '') + '&note=' + (currentCustomer.note || '') +
                    '&sex=' + (sex || '') + '&age=' + (currentCustomer.age || '') + '&birth=' + (currentCustomer.birth || '')
          } else { // 企业版
            message += '&name=' + (currentCustomer.name || '') + '&status=' + (custStatusName || '') + '&title=' + (currentCustomer.title || '') + '&phone=' + this.arrToStr(currentCustomer.phone, 'tel') + '&callPhone=' + this.arrToStr([{calledTel, memo: ''}], 'calledTel') +'&email=' + this.arrToStr(currentCustomer.email, 'email') +
                    '&weixin=' + this.arrToStr(currentCustomer.weixin, 'num') + '&province=' + (province || '') + '&city=' + (city || '') + '&address=' + (currentCustomer.address || '') + '&note=' + (currentCustomer.note || '') +
                    '&web=' + (currentCustomer.web || '')
          }
          if (account.encryptionCheck) { // 开启敏感数据
            message += this.shunfengdingzhi(callPhone)
          }
        } else if (callInfo && callInfo.CONNECT_TYPE) { // 定位不到客户时并且有CONNECT_TYPE
          let callPhone = ''
          let calledPhone = ''
          if (callInfo.CONNECT_TYPE === 'dialout' || callInfo.CONNECT_TYPE === 'dialTransfer') {
            callPhone = callInfo.CALLED_NO
            calledPhone = callInfo.CALL_NO
          } else {
            callPhone = callInfo.CALL_NO
            calledPhone = callInfo.CALLED_NO
          }
          message += this.handleEncryptPhone(callPhone, calledPhone)
        }
        message += '&displayName=' + diaplayName + '&exten=' + exten + '&callSheetId=' + callSheetId + '&accountId=' + this.$store.state.session.account.account
        if (this.$store.state.session.account.tokenCheck) {
          message += '&token=' + (this.token.token || '') + '&tokenId=' + (this.token.tokenId || '')
        }
        if (url && (url.indexOf('power.7moor.com') > -1 || url.indexOf('power-') > -1)) {
          if (this.$store.state.session.sessionId && window.sessionStorage.getItem('loginToken')) {
            message += '&sessionId=' + this.$store.state.session.sessionId + '&loginToken=' + window.sessionStorage.getItem('loginToken')
          }
        }
        if (account.encryptionCheck && account.encryType === 'aes') { // 开启隐私加密 && aes加密
          message += `&${account.aesOffsetKey || 'iv'}=${account.aesOffsetValue}`
        }
        if (message.indexOf('#') !== -1) {
          message = message.replace(/#/g, '%23')
        }
        url += message
        if (isEncode) {
          url = encodeURI(url)
        }
        return url.replace('http://', '//').replace('${customerId}', this.currentCustomer ? this.currentCustomer._id : '')
      },
      handleEncryptPhone (callPhone, calledPhone) {
        let account = this.$store.state.session.account
        let str = ''
        if (account.encryptionCheck) { // 开启敏感数据
          if (account.encryType === 'aes') { // aes加密
            str += this.shunfengdingzhi(callPhone) // 顺丰定制
            callPhone = getAesEncrypt(account.aesSecret, account.aesOffsetValue, callPhone)
            calledPhone = getAesEncrypt(account.aesSecret, account.aesOffsetValue, calledPhone)
          } else { // 默认加密
            let secretKey = account.secretKey
            callPhone = encrypt(secretKey, callPhone)
            calledPhone = encrypt(secretKey, calledPhone)
          }
        }
        str += '&phone=' + callPhone + '&callPhone=' + calledPhone
        return str
      },
      shunfengdingzhi (callPhone) {
        let account = this.$store.state.session.account
        let str = ''
        if (['T00000022274', 'T00000024274', 'T00000000003'].includes(account.account) && account.encryType === 'aes') { // 顺丰定制 && 开启了aes加密
          callPhone = getAesEncrypt(account.aesSecret, account.aesOffsetValue, callPhone)
          str += `&mobile=${callPhone}`
          str += `&timestamp=${this.timestamp}`
          const token = 'a4e5ef7c-3bae-4ed8-b1bc-66766fe379ff' // 顺丰提供的固定的token用于加密sign
          const sign = md5(token + this.timestamp)
          str += `&sign=${sign}`
        }
        return str
      },
      arrToStr (arr, field) {
        let account = this.$store.state.session.account
        let encryptionCheck = account.encryptionCheck
        if (!Array.isArray(arr)) {
          return ''
        }
        let str = ''
        for (let i = 0; i < arr.length; i++) {
          if (encryptionCheck && (field === 'tel' || field === 'calledTel')) {
            if (account.encryType === 'aes') { // aes加密
              str += getAesEncrypt(account.aesSecret, account.aesOffsetValue, arr[i][field]) + ','
            } else { // 默认加密
              let secretKey =account.secretKey
              str += encrypt(secretKey, arr[i][field]) + ','
            }
          } else {
            str += arr[i][field] + ','
          }
        }
        if (str.indexOf(',') !== -1) {
          str = str.substring(0, str.lastIndexOf(','))
        }
        console.log(str, '=========')
        return str
      },
      mergeCustomer (val) { // 合并客户
        let routes = this.$route.path.split('/')
        let tabType = routes[3]
        let callId = routes[4]
        this.$store.commit('call/REFRESH_CUST_RIGHT', Math.random())
        if (tabType === 'cdr_outbound') {
          this.mergeOutboundCustomer(val, callId)
        } else {
          let data = {
            customerId: val._id,
            callId: this.$route.params.id,
            custName: val.name,
            customer: val.custInfo,
            submenu: tabType,
            sessionId: this.$route.path.split('/')[4]
          }
          this.$store.dispatch('callLocationCustomer', data).then(resp => {
            if (resp && resp.success) {
              this.isDailog = false
              this.$message({
                type: 'success',
                message: this.$t('customer.succMerge')
              })
            }
          })
        }
      },
      mergeOutboundCustomer (val, callId) { // 合并客户
        let phoneArr = val.custInfo.phone
        let phoneFlag = false
        let callInfo = this.$store.state.call.current[this.tabType].callInfo || {}
        if (phoneArr) {
          for (let i = 0; i < phoneArr.length; i++) {
            if (phoneArr[i].tel === callInfo.CALLED_NO) {
              phoneFlag = true
              break
            } else {
              phoneFlag = false
            }
          }
        }
        if (phoneFlag) { // 点击保存按钮之后直接合并客户
          this.mergeCustomerNow(val, callId, callInfo.CALLED_NO)
        } else { // 合并的客户没有当前号码,先把号码更新过去之后再合并
          let newPhoneObj = {tel: callInfo.CALLED_NO, memo: ''}
          // 当这个用户没有电话时，没有phone字段
          if (!val.custInfo.phone) {
            val.custInfo.phone = []
          }
          val.custInfo.phone.push(newPhoneObj)
          this.updateCustomer(val, callId, callInfo.CALLED_NO)
        }
      },
      mergeCustomerNow (val, callId, phone) {
        let data = {
          customerId: val._id,
          callId: callId,
          phone: phone,
          dealSrc: 'dialPopup',
          sessionId: this.$store.state.session.sessionId
        }
        this.$store.dispatch('callScreenLocationCustomer', data).then(resp => {
          this.isDailog = false
          this.$message({
            type: 'success',
            message: this.$t('customer.succMerge')
          })
          this.$store.commit('call/UPDATE_CURRENT_CUSTOMER_INFO', {callId: data.callId, customer: val.custInfo})
          this.$store.commit('call/TEMP_CUSTOMER_DATA', {callId: data.callId, customer: val.custInfo})
        })
      },
      updateCustomer (val, callId, phone) { // 先更新客户再合并
        let data = val.custInfo || {}
        data.type = 'customer'
        data.tabType = 'customer_my'
        data.callId = callId
        this.$store.dispatch('updateCustomer', data).then((resp) => {
          if (!resp) {
            return
          }
          this.mergeCustomerNow(val, callId, phone)
        })
      },
      handlerChangeTab (tabName) { // tab切换
        this.tabActiveName = tabName
        this.refresh = tabName
        if (tabName === 'business') {
          this.busId = ''
          if (this.businessFirstIn) { // 第一次进入工单时才加载工单数据，tab再次切换不加载
            this.reloadBussiness = Math.random()
            this.businessFirstIn = false
          }
        }
        if (tabName.indexOf('-') > -1) {
          this.tabCount += 1
        }
        if (tabName === 'callDetail') {
          this.callCount += 1
        }
      },
      queryToolbarFun (callback) {
        let p1 = this.$store.dispatch('queryToolbarTabPosition', {module: 'call'})
        let p2 = this.$store.dispatch('getCache', {type: 'options'}) // 字典 eg:省市
        let p3 = this.$store.dispatch('getCache', {type: 'custTmpls'}) // 客户配置
        let p4 = this.$store.dispatch('getCache', {type: 'agents'}) // 所有坐席
        let p5 = this.$store.dispatch('getCache', {type: 'tabUrlAddress'}) // tab对接
        Promise.all([p1, p2, p3, p4, p5]).then(([res]) => {
          if (res && res.data) {
            let routes = this.$route.path.split('/')
            let tabType = routes[3]
            this.tabType = tabType
            let normalTab = []
            let list = res.data || []
            let toolbarTabArr = []
            for (let i = 0; i < list.length; i++) {
              if ('show' in list[i] && !list[i].show) {
                continue
              }
              if (list[i].businesses || list[i].url) {
                toolbarTabArr.push(list[i])
                if ('editable' in list[i]) {
                  normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, type: 'toolbar'})
                } else {
                  normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, url: list[i].url, isEncode: list[i].isEncode})
                }
              } else {
                  if (list[i].tabName === 'contactPlan') {
                    normalTab.push({_id: list[i]._id, disabled: false, name: 'plan', slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
                  } else if (list[i].tabName === 'changeLog') {
                    if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_operation_log')) {
                      if (this.$store.state.session.account.isSouthEastAsia !== 'true') {
                        normalTab.push({
                          _id: list[i]._id,
                          disabled: false,
                          name: 'changeLog',
                          slotName: 'changeLogTab',
                          labelName: this.$t('public.changeLog')
                        })
                      }
                    }
                  } else if (list[i].tabName === 'history') {
                    if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_contact_history')) {
                      normalTab.push({disabled: false, name: 'history', slotName: 'historyTab', labelName: this.$t('public.history'), _id: list[i]._id})
                    }
                  } else if ( tabType && tabType === 'cdr_outbound' && list[i].tabName === 'callDetail') {
                    normalTab.splice(i, 1)
                  } else {
                    if (list[i].tabName) {
                      normalTab.push({_id: list[i]._id, disabled: false, name: list[i].tabName, slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
                    }
                  }
                }
              }
            this.toolbarTab = toolbarTabArr
            this.tabs2.normalTab = normalTab
            if(!this.showTabIntelligent){
              this.tabs2.normalTab = this.tabs2.normalTab.filter(item=>{
                return item.name !== 'goldenSession'
              })
            }
            this.intelligentData = deepClone(normalTab)
            this.tempTab = this.intelligentData.filter(item=>{
              return item.name == 'goldenSession'
            })
          }
          this.refresh = this.tabs2.normalTab[0].slotName ? this.tabs2.normalTab[0].name : this.tabs2.normalTab[0]._id
          this.tabActiveName = this.tabs2.normalTab[0].slotName ? this.tabs2.normalTab[0].name : this.tabs2.normalTab[0]._id

          this.tabUrls = this.toolbarTab
          if (this.refresh.indexOf('-') > -1) {
            this.tabCount = 2
          }
          if (this.refresh === 'callDetail') {
            this.callCount += 1
          } else {
            this.callCount = 0
          }
          if (callback) {
            callback()
          }
        })
      }
    },
    // mounted () {
    //   bus.$on('callUpdateCustomer', ()=> {
    //     this.editCustomer()
    //   })
    // },
    activated () {
      this.queryToolbarFun()
    },
    beforeMount () {  // 组件加载之前
      this.queryToolbarFun(() => {
        this.fetchData()
      })
    }
    // beforeDestroy () {
    //   bus.$off('callUpdateCustomer')
    // }
  }
</script>
